package org.cosmact.designer.vxml.gefeditor.editpart.command;

import org.cosmact.vxml.model.Dialog;
import org.cosmact.vxml.model.DialogConnection;
import org.cosmact.vxml.model.ModelFactory;
import org.eclipse.gef.commands.Command;

public class ConnectionCreateCommand extends Command {
    /** The connection instance. */
    private DialogConnection connection;
    /** The desired line style for the connection (dashed or solid). */
    private final int lineStyle;

    /** Start endpoint for the connection. */
    private final Dialog source;
    /** Target endpoint for the connection. */
    private Dialog target;

    /**
     * Instantiate a command that can create a connection between two shapes.
     * 
     * @param source
     *            the source endpoint (a non-null Shape instance)
     * @param lineStyle
     *            the desired line style. See Connection#setLineStyle(int) for
     *            details
     * @throws IllegalArgumentException
     *             if source is null
     * @see Connection#setLineStyle(int)
     */
    public ConnectionCreateCommand(Dialog source, int lineStyle) {
	if (source == null) {
	    throw new IllegalArgumentException();
	}
	setLabel("connection creation");
	this.source = source;
	this.lineStyle = lineStyle;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.gef.commands.Command#canExecute()
     */
    @Override
    public boolean canExecute() {
	// disallow source -> source connections
	if (source.equals(target)) {
	    return false;
	}
	// Allow multi connection between same source and target
	return true;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.gef.commands.Command#execute()
     */
    @Override
    public void execute() {
	// create a new connection between source and target
	connection = ModelFactory.eINSTANCE.createDialogConnection();
	// Set default connection type
	connection.setConnectionType(ModelFactory.eINSTANCE
		.createDialogConnectionType());
	connection.reconnect(source, target);
	// TODO Line style define
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.gef.commands.Command#redo()
     */
    @Override
    public void redo() {
	connection.reconnect();
    }

    /**
     * Set the target endpoint for the connection.
     * 
     * @param target
     *            that target endpoint (a non-null Shape instance)
     * @throws IllegalArgumentException
     *             if target is null
     */
    public void setTarget(Dialog target) {
	if (target == null) {
	    throw new IllegalArgumentException();
	}
	this.target = target;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.gef.commands.Command#undo()
     */
    @Override
    public void undo() {
	connection.disconnect();
    }
}
